package organization

import (
	"context"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/organization/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"
)

func (c *ControllerV1) List(ctx context.Context, req *v1.ListReq) (res *v1.ListRes, err error) {
	tenantCode := ctx.Value(consts.TokenClaims.TenantCode).(string)
	res = &v1.ListRes{}
	in := &v1.ListInput{}
	in.TenantCode = tenantCode
	// 先查询所有节点
	out, err := service.Organization().List(ctx, in)
	if err != nil {
		return nil, err
	}
	orgMap := make(map[int64]*v1.Org, 0)
	for _, o := range out.Data {
		orgMap[o.Id] = &v1.Org{
			Code:     o.Code,
			Id:       o.Id,
			Name:     o.Name,
			Parent:   o.Parent,
			Type:     o.Type,
			Children: make([]*v1.Org, 0),
		}
	}
	var roots []*v1.Org
	for _, o := range out.Data {
		node := orgMap[o.Id]
		if o.Parent == 0 {
			roots = append(roots, node)
		} else if parent, exists := orgMap[o.Parent]; exists {
			parent.Children = append(parent.Children, node)
		}
	}
	res.Data = roots
	return res, nil
}
